package cn.candy.order.service.impl;

import cn.candy.basic.service.impl.BaseServiceImpl;
import cn.candy.basic.util.CodeGenerateUtils;
import cn.candy.basic.util.LoginContextUtil;
import cn.candy.basic.util.PageList;
import cn.candy.order.domain.AdoptOrder;
import cn.candy.order.domain.OrderAddress;
import cn.candy.order.mapper.AdoptOrderMapper;
import cn.candy.order.mapper.OrderAddressMapper;
import cn.candy.order.query.AdoptOrderQuery;
import cn.candy.order.service.IAdoptOrderService;
import cn.candy.org.domain.Employee;
import cn.candy.org.mapper.EmployeeMapper;
import cn.candy.pay.constants.PayConstants;
import cn.candy.pay.domain.PayBill;
import cn.candy.pay.mapper.PayBillMapper;
import cn.candy.pay.service.IPayBillService;
import cn.candy.pet.domain.Pet;
import cn.candy.pet.mapper.PetMapper;
import cn.candy.user.domain.Logininfo;
import cn.candy.user.domain.User;
import cn.candy.user.domain.UserAddress;
import cn.candy.user.mapper.UserAddressMapper;
import cn.candy.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 领养订单业务实现
 */
@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    /**
     * 处理领养订单
     * @param params
     * @param request
     * @return
     */
    @Override
    public String adoptOrderSubmit(Map<String, Object> params, HttpServletRequest request) {
        Long petId = Long.parseLong(params.get("pet_id").toString());
        //1.下架并设置下架时间
        Pet pet = petMapper.loadById(petId);
        pet.setState(0);
        pet.setOffsaletime(new Date());

        //2.绑定用户id
        Logininfo logininfo = LoginContextUtil.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        pet.setUser_id(user.getId());
        pet.setUser(user);
        //修改新的状态
        petMapper.update(pet);

        //送货方式 - 默认送宠上门
        Integer service_method = Integer.parseInt(params.get("service_method").toString());
        //支付方式
        Long payType = Long.parseLong(params.get("pay_method").toString());
        //用户的地址id
        Long addressId = Long.parseLong(params.get("address_id").toString());

        //3.生成订单
        //3.1.创建订单 - 通过pet对象和 user对象生成
        AdoptOrder adoptOrder = petUser2AdoptOrder(pet,user);
        adoptOrderMapper.save(adoptOrder);//自增长

        //3.2.根据address_id获取用户地址 拷贝 给订单地址
        //3.3.订单地址对象中设置订单id和orderSn
        //3.4.添加到数据库【订单地址不会变化，但是用户的地址可以变化】
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = userAddress2OrderAddress(userAddress,adoptOrder);
        orderAddressMapper.save(orderAddress);

        //4.支付 @TODO
        //4.1.创建支付单
        PayBill payBill = initPayBill(user, payType, adoptOrder);
        payBillMapper.save(payBill);
        //4.2.调用第三方的支付接口【支付宝】去支付
//        AlipayUtil.pay()
        String payData = payBillService.payRequest(payBill);
        return payData;
    }

    private PayBill initPayBill(User user, Long payType, AdoptOrder adoptOrder) {
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest());
        payBill.setMoney(adoptOrder.getPrice());
        payBill.setLastPayTime(new Date(System.currentTimeMillis() + 15*60*1000));
        payBill.setPayChannel(payType); //支付宝支付
        payBill.setUnionPaySn(adoptOrder.getPaySn());
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);
        payBill.setBusinessKey(adoptOrder.getId());
        payBill.setUser_id(user.getId());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(adoptOrder.getShop_id());
        return payBill;
    }

    /**
     * 查询管理员领养订单
     * @param adoptOrderQuery
     * @param request
     * @return
     */
    @Override
    public PageList<AdoptOrder> adminAdoptOrder(AdoptOrderQuery adoptOrderQuery, HttpServletRequest request) {
        Logininfo logininfo = LoginContextUtil.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        adoptOrderQuery.setShopId(employee.getShop_id());

        return super.queryPage(adoptOrderQuery);
    }

    /**
     * 查询用户领养订单
     * @param adoptOrderQuery
     * @param request
     * @return
     */
    @Override
    public PageList<AdoptOrder> userAdoptOrder(AdoptOrderQuery adoptOrderQuery, HttpServletRequest request) {
        Logininfo logininfo = LoginContextUtil.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        adoptOrderQuery.setUserId(user.getId());

        return super.queryPage(adoptOrderQuery);
    }

    /**
     * 转成领养订单方法
     * @param pet
     * @param user
     * @return
     */
    private AdoptOrder petUser2AdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        order.setState(0);//待支付 以支付1 取消-1
        order.setPrice(pet.getSaleprice()); //领养订单设置销售价
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        //paySn - 支付单唯一单号 - 支付的时候做
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        order.setPaySn(paySn);
        //最后支付时间 - 24小时不支付就取消
        order.setLastPayTime(new Date(System.currentTimeMillis() + 15*60*1000));
        //lastcomfirmtime - 支付之后再整
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        //lastcomfirmtime - 店铺给用户 - 不用倒计时定时器
        return order;
    }


    /**
     * 转订单地址方法
     * @param userAddress
     * @param adoptOrder
     * @return
     */
    private OrderAddress userAddress2OrderAddress(UserAddress userAddress, AdoptOrder adoptOrder) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);

        orderAddress.setOrder_id(adoptOrder.getId());
        orderAddress.setOrderSn(adoptOrder.getOrderSn());

        orderAddress.setCreateTime(new Date());
        return orderAddress;
    }
}
